package com.magicode.screen.thirdPart.wx;

import android.app.Activity;
import android.support.annotation.Nullable;
import android.widget.Toast;

import com.facebook.react.ReactInstanceManager;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.magicode.screen.AppConfig;
import com.magicode.screen.AppContext;
import com.magicode.screen.api.ApiHttpClient;
import com.magicode.screen.api.remote.MgcApi;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.apache.http.Header;
import org.apache.http.protocol.HttpContext;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付实现类，包括以下步骤；
 * 1.下单，在服务器端创建创建订单；
 * 2.通知微信/支付宝进行支付；
 * 3.等待微信/支付宝支付结束后返回，检查服务器端状态；
 *  如果支付成功，但服务器端未支付，等待一段时间再次发送请求；连续发送三次请求未果，提示支付出现问题；
 * Created by wxt on 2017/9/12.
 */
public class WxPayUtil  {
    private Activity currentActivity;
//    静态变量，供activity使用
    public static String outTradeId;
    /**
     * 预支付Handler
     */
    private final AsyncHttpResponseHandler prePayHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
            try {
                AsyncHttpClient client = ApiHttpClient.getHttpClient();
//                HttpContext httpContext = client.getHttpContext();
                ObjectMapper mapper = new ObjectMapper();
                Map result = mapper.readValue(arg2, HashMap.class);
                Map entity = null;
                String status = (String) result.get("status");
                String message = (String) result.get("message");
                if("99".equals(status)) {
                    if (result != null) {
                        entity = (Map) result.get("entity");
                    }
                    Map readyToPayMap = null;
                    if (entity != null) {
                        readyToPayMap = (Map) entity.get("readyToPay");
                    }
                    if ( entity != null && readyToPayMap != null) {
                        outTradeId = (String) entity.get("outTradeId");
//                        String payStatus = (String) readyToPayMap.get("status");
                        String appid = (String) readyToPayMap.get("appid");
                        String partnerid = (String) readyToPayMap.get("partnerid");
                        String prepayid = (String) readyToPayMap.get("prepayid");
                        String packageValue = (String) readyToPayMap.get("package");
                        String noncestr = (String) readyToPayMap.get("noncestr");
                        String timestamp = (String) readyToPayMap.get("timestamp");
                        String sign = (String) readyToPayMap.get("sign");
                        pay(getCurrentActivity(), prepayid, packageValue, noncestr, timestamp, sign);
                    }
                }else{
                    AppContext.showToast(message);
                }
            } catch (Exception e) {
                e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
            }
        }
        @Override
        public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                              Throwable arg3) {
			AppContext.showToast("下单错误");
        }
    };

    /**
     * 提交支付宝
     * @param currentActivity
     * @param prepayId
     * @param packageValue
     * @param nonceStr
     * @param timeStamp
     * @param sign
     */
    public void pay(Activity currentActivity , String prepayId , String packageValue , String nonceStr , String timeStamp , String sign){
        IWXAPI api = WXAPIFactory.createWXAPI(currentActivity, AppConfig.APP_WX_KEY, false);
        this.currentActivity = currentActivity;
//        api.handleIntent(currentActivity.getIntent(), this);
        if (!api.isWXAppInstalled()) {
            //提醒用户没有按照微信
            Toast.makeText(currentActivity, "没有安装微信,请先安装微信!", Toast.LENGTH_SHORT).show();
            return;
        }
        else{
            PayReq request = new PayReq();
            request.appId = AppConfig.APP_WX_KEY;
            request.partnerId = AppConfig.APP_WX_PAY_PartnerId;
            request.prepayId = prepayId;
            request.packageValue = packageValue;
            request.nonceStr = nonceStr;
            request.timeStamp = timeStamp;
            request.sign = sign;
            api.sendReq(request);
        }
    }

    public AsyncHttpResponseHandler getPrePayHandler(){
        return this.prePayHandler;
    }
    public Activity getCurrentActivity() {
        return currentActivity;
    }
    public void setCurrentActivity(Activity currentActivity) {
        this.currentActivity = currentActivity;
    }
}
